/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.HTMLUIcomponents;

import java.util.ArrayList;

import model.DHTMLConstants;
import model.Labels;
import model.Vocabulary;

import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;

import controller.HelperFunctions;
import controller.elementMapper.ClassMapper;
import controller.elementMapper.Mapper;

public class BelongsToOM extends AbstractComponent {
	

	private static final String CSSIDFIELD = "divbelongstoom";
	public static final String CSSIDCONTENT = "divbelongstoomcontent";
	public static final String NAMEFORMELEMENT = "belongsToOntologyModuleEntry";
	public static final String NAMEFORMELEMENTTREE = "OntologyModuleSearchTree";
	
	
	/**
	 * Returns the field in view mode.
	 * @param id
	 * @param entry
	 * @return
	 */
	public static String getFieldInViewMode(  URI uri, boolean showNavigation, boolean showNavigationInEditMode ) throws Exception {
		String ret = "";

		ret += getTitleContainer( Labels.BELONGSTOONTOLOGYMODULE, DHTMLConstants.ONTOLOGY_VIEWTYPE, false, true );
		ret += getFormContainer( getFormInViewMode( uri, showNavigation, showNavigationInEditMode ), CSSIDCONTENT );

		// The field is printed in <div id=" fieldIdentifier "> and hence all its components can be accessed with this
		ret = getFieldContainer( ret, CSSIDFIELD );
		
		return ret;
	}
	
	/**
	 * Returns the field in view mode.
	 * @param id
	 * @param entry
	 * @return
	 */
	public static String getFieldInEditMode(  URI uri, ArrayList<URI> entryList, ArrayList<Exception> exceptions, boolean showNavigation, boolean showCreateLinks ) throws Exception {
		String ret = "";

		ret += getTitleContainer( Labels.BELONGSTOONTOLOGYMODULE, DHTMLConstants.ONTOLOGY_VIEWTYPE, false, true );
		ret += getFormContainer( getFormInEditMode( uri, entryList, exceptions, showNavigation, showCreateLinks ), CSSIDCONTENT );

		// The field is printed in <div id=" fieldIdentifier "> and hence all its components can be accessed with this
		ret = getFieldContainer( ret, CSSIDFIELD );
		
		return ret;
	}
	
	public static String getFormInViewMode( URI uri, boolean showNavigation, boolean showNavigationInEditMode ) throws Exception {

		String ret = "";	

		java.util.ArrayList<URI> list = ClassMapper.selectBelongsToOM( uri );
		String content = getElementsHTMLList( list );	

		ret = renderViewForm( 
				content, 			
				// Mapper.selectHasVersionDateTimeString(uri),
				HelperFunctions.concatURIsReachable( ClassMapper.selectBelongsToOM(uri) ), // workaround
				CSSIDCONTENT, 
				showNavigation,
				showNavigationInEditMode );
		
		return ret;
	}
	
	

	
	public static String getFormInEditMode( URI uri, ArrayList<URI> entryList, ArrayList<Exception> exceptions, boolean showNavigation, boolean showCreateLinks ) throws Exception {
		
		String ret = "";

		String actualVersionContent = NOTHINGSELECTED;
		// String actualTimestamp = Mapper.selectHasVersionDateTimeString(uri);
		String oldentry = HelperFunctions.concatURIsReachable( ClassMapper.selectBelongsToOM( uri ) );

		
		if( uri!=null ) {	

			java.util.ArrayList<URI> tmp = ClassMapper.selectBelongsToOM( uri );			
			if( tmp!=null ) {				
				actualVersionContent = getElementsHTMLList( tmp );					
			}
		}
				
		String createNewAdditionalParams = ClassesBelongingToOM.NAMEFORMELEMENT + "=" + HelperFunctions.getUriForHref( uri );
		
		String content = getItemsEditPanel( NAMEFORMELEMENT, entryList, DHTMLConstants.ONTOLOGY_VIEWTYPE, createNewAdditionalParams, showCreateLinks );

		ret = renderEditForm( 
			Labels.BELONGSTOONTOLOGYMODULE, 
			content,
			exceptions, 
			actualVersionContent, 
			//actualTimestamp,
			oldentry, // workaround
			CSSIDCONTENT, 
			NAMEFORMELEMENT, 
			showNavigation );


		return ret;
	}
	

	/**
	 * returns HTML-code containing a selectBox f�r belongsToOM, Domain, Range
	 * @param nameFormElement	The Name of the field, where the selected Items can be queried out of request.getParameterByName(...)
	 * @param elementEntry	List of preselected elements separated by a comma ("element1,element2,")
	 * @param selectableItems	Arraylist containing the ID and the Label of all Elements which can be selected.
	 * @return
	 */
	protected static String getSelectBox( String nameFormElement, String elementEntry, java.util.ArrayList<URI> selectableItems, URI uri ) {
		
		
		String ret = 
			"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"1\">\n"+
			"	<tr>\n"+
			"		<td>Selected:<br /></td>\n"+
			"		<td></td>\n"+
			"		<td>Items:<br /></td>\n"+
			"	</tr>\n"+
			"	<tr>\n"+
			"		<td valign=\"top\">\n" +
			"			<select size=\"8\" multiple=\"multiple\" name=\"" + nameFormElement + "_list\" class=\"leftselectbox\">\n";
		

		try {
			// the actual values	
			String[] strarray = elementEntry.split( HelperFunctions.DEFAULTPLITTER );
			for( int i = 0; i<strarray.length; i++ ){
				
				if( !strarray[i].equals("") ) {

					try {
						String label = Mapper.selectLabel( new URIImpl( strarray[i] ), Vocabulary.ENGLISH );

						ret += 
			"				<option value=\"" + strarray[i] + "\">" + label + "</option>\n";
					}
					catch( Exception e ) {					
						logger.error(e);		
					}		
					
				}
			}
		}
		catch( Exception e )
		{
			logger.error( e );
		}
			
		ret +=
			"			</select>\n" +
			"		</td>\n"+
			"		<td valign=\"top\"><a href=\"\" onClick=\"setFormValueManipulate('" + nameFormElement + "','Remove'); return false\"><img src=\"skins/default/images/garbage.gif\" style=\"margin-right:10px; border:none;\" onmouseover=\"myTip('Remove item(s) from selected ones (first mark!)')\" /></a></td>\n"+
			"		<td valign=\"top\">\n";
		
		/*
		if( selectableItems.size()<5 ) {
			ret +=
				"			<select name=\"" + nameFormElement + "_sel\" size=\"8\" onChange=\"setFormValueFromBrowseWin('" + nameFormElement + "',this.options[this.selectedIndex].value,this.options[this.selectedIndex].text); \" class=\"rightselectbox\">\n";
			
			
				
	
			try {
				 // the values which can be selected:
				
				for( int i=0; i< selectableItems.size(); i++ ) {
					ret+=
				"				<option value=\"" + selectableItems.get(i).stringValue() + "\">" + Mapper.selectLabel( selectableItems.get(i), Vocabulary.ENGLISH ) + "</option>\n";
				}
			}
			catch( Exception e )
			{
				System.out.println( e );
			}
		}
		else {
	*/
			String autocomplete = "";
			String additionalparameters = "type=" + Vocabulary.ONTOLOGYMODULE + "&actionCode="+DHTMLConstants.SUGGEST;
			
			autocomplete += "<div style=\"width:300px;\"><input style=\"width:240px;\" onkeyup=\"disableButtonOnValueNull('" + nameFormElement + "_receivedId','" + nameFormElement + "_adderbutton');\" onfocus=\"activateAutocompleter(this.id,'" + nameFormElement + "_receivedId','AjaxXmlGenerator','" + additionalparameters+ "',true )\" autocomplete=\"off\" id=\"" + nameFormElement + "_adder\" name=\"" + nameFormElement + "_adder\" type=\"text\" value=\"\" onkeypress=\"return noEnter(event)\" />" +
			//		"<img style=\"cursor:pointer;\" src=\"skins/default/images/add.png\" alt=\"add\" title=\"Add\" border=\"0\" onclick=\"javascript:if(document.getElementById('" + nameFormElement + "_receivedId').value=='') { alert('To add a new " + Labels.ONTOLOGY.getNameSingular() + " first create one!'); } else { setFormValueFromBrowseWin('" + nameFormElement + "',document.getElementById('" + nameFormElement + "_receivedId').value,document.getElementById('" + nameFormElement + "_adder').value );}\" /></div>";
					" <input id=\"" + nameFormElement + "_adderbutton\" disabled=\"true\" type=\"button\" value=\"Add\" onclick=\"buttonAddToListClick( '" + nameFormElement + "', '" + nameFormElement + "_receivedId', '"+ nameFormElement +"_adder', '" + Labels.ONTOLOGY.getNameSingular() + "');\" /></div>";
			
			autocomplete += "\n<input type=\"hidden\" id=\"" + nameFormElement + "_receivedId\" name=\"" + nameFormElement + "_receivedId\" value=\"\" />";
				
			String struri = "";
			if( uri!=null )
				struri = uri.stringValue();
				
			//autocomplete += "\n<div><a href=\"newOntologyModule\" target=\"_blank\">Create new " + Labels.ONTOLOGY.getNameSingular() +"</a></div>";
			// autocomplete += "\n<div><a href=\"#\" onclick=\"window.location='newOntologyModule/?labelEntry='+document.getElementById('" + nameFormElement + "_adder').value+'&"+ClassesBelongingToOM.NAMEFORMELEMENT+"="+ struri +"'; return false;\">Create new " + Labels.ONTOLOGY.getNameSingular() +"</a></div>";

			ret += autocomplete;
	//	}
			
		
		
		ret +=
			"			</select>\n";
		
		
			
		ret +=
			"		</td>\n"+
			"	</tr>\n"+
			"</table>\n";

		// the actual values (again; this field is filled / decreased with DHTML but has to be "initialized")
		ret +=
			"<input type=\"hidden\" name=\"" + nameFormElement + "\" value=\"" + elementEntry + "\" />\n";

		
		return ret;
	}
	

	public static String getSelectBoxOM() {
		String autocomplete = "";
		String additionalparameters = "viewtype=" + DHTMLConstants.ONTOLOGY_VIEWTYPE + "&actionCode="+DHTMLConstants.SUGGEST;
		String functionchangeom = "setOMValueForGlobalTree()";
		
		autocomplete += "\n<input type=\"hidden\" id=\"" + NAMEFORMELEMENTTREE + "_receivedId\" name=\"" + NAMEFORMELEMENTTREE + "_receivedId\" value=\"\" />";			
		//autocomplete += "<div style=\"width:150px;overflow:hidden;\">";
		autocomplete += "<div style=\"width:150px;\">";
		autocomplete += "<p>restrict by<br>";
//		autocomplete += "<input style=\"width:140px;\" onblur=\"searchboxOnBlur('" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "','" + NAMEFORMELEMENTTREE + "_receivedId','');"+functionchangeom+"\" onfocus=\"searchboxOnFocus('" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "','"+additionalparameters+"','" + NAMEFORMELEMENTTREE + "_receivedId','',true,'')\" autocomplete=\"off\" id=\"" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"\" onkeypress=\""+functionchangeom+";return noEnter(event)\">";
		autocomplete += "<input class=\"suggestbox\" onblur=\"searchboxOnBlur('" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "','" + NAMEFORMELEMENTTREE + "_receivedId','');"+functionchangeom+"\" onfocus=\"searchboxOnFocus('" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "','"+additionalparameters+"','" + NAMEFORMELEMENTTREE + "_receivedId','',true,'')\" autocomplete=\"off\" id=\"" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + NAMEFORMELEMENTTREE + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"\" onkeypress=\""+functionchangeom+";return noEnter(event)\">";		
		autocomplete += "</div>";
		autocomplete += "</p>";
		

		return autocomplete;
	}
}
